<?php
namespace Api\Controller;
vendor('Firebase.JWT.JWT');

class AdminController extends BaseController {
    //用户名密码登录
    public function login() {
        if (!$_POST) {
            fail("需要post请求");
        }
        $data = get_trim_data(get_auto_data($_REQUEST));
        $username = $data['username'];
        $password = $data['password'];
        if (!$username) {
            fail_name('参数错误', 'username');
        }
        if (!$password) {
            fail_name('参数错误', 'password');
        }
        //查找用户
        $admin_user = M('admin_user')->field('uid,password,salt,phone,nick_name,gender,age,head_img')->where(array(
            'username' => $username
        ))->find();
        if (!$admin_user) {
            fail('用户不存在');
        }
        //判断密码是否正确
        if (jiami($password . $admin_user['salt']) != $admin_user['password']) {
            fail('密码错误');
        }
        //生成token并返回
        $token ['uid'] = $admin_user['uid'];
        $token ['time'] = time();
        $jwt = \Firebase\JWT\JWT::encode($token, C('COOKIE'));
        $admin_user['token'] = $jwt;
        unset($admin_user['password']);
        succeed(get_auto_data($admin_user));
    }
}